package it.infodea.tapestrydea.components.livegrid;

import org.apache.tapestry5.Block;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.corelib.components.EventLink;
import org.apache.tapestry5.corelib.components.GridRows;
import org.apache.tapestry5.internal.InternalConstants;
import org.apache.tapestry5.ioc.annotations.Inject;

public class LGridRows extends GridRows {
	
    public static final String ON_DELETE_ROW_EVENT = "deleteRow";

	@SuppressWarnings("unused")
    @Component(
            parameters = {"event=remove", "context=rowContext", 
                    "zone=inherit:zone"})
    private EventLink remove;

    private int rowIndex;

    @Inject
    private Block standardCell;

    @Inject
    private Block lGridRemoveCell;
    /**
     * Number of rows displayed on each page. Long result sets are split across multiple pages.
     */
    @Parameter(required = true)
    private int rowsPerPage;

    /**
     * The current page number within the available pages (indexed from 1).
     */
    @Parameter(required = true)
    private int currentPage;

    @Parameter
    private String zone;
	
    @Parameter
    private String removeLabel;
    
    @Inject
    private ComponentResources resources;
    /**
     * Normal, non-Ajax event handler.
     */

    void onRemove(int rowId) {
    	int index = ((currentPage - 1) * rowsPerPage) + rowId;
    	resources.triggerEvent(ON_DELETE_ROW_EVENT, new Object[] {index}, null);
    }

    /**
     * Ajax event handler, which carries the zone id.
     */
    @OnEvent("remove")
    boolean onRemove(int rowId, String zone)
    {
    	onRemove(rowId);
        resources.triggerEvent(InternalConstants.GRID_INPLACE_UPDATE, new Object[] {zone}, null);
        return true;
    }

	public Object getRowContext(){
        if (zone == null) return rowIndex;
		return new Object[]{rowIndex++, zone};
	}

	public Block getCellBlock(){
		if(!LGrid.REMOVE_COLUMN_NAME.equals(getPropertyName())){
			return standardCell;
		}else{
			return lGridRemoveCell;
		}
	}

	public String getRemoveLabel() {
		return removeLabel;
	}

}
